package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.ChannelService;
import com.lkd.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
@Topic("server/vms/supply")
public class SupplyMsgHandler implements MsgHandler {

    @Autowired
    private ChannelService channelService;

    @Override
    public void process(String jsonMsg) throws IOException {
        System.err.println("接收到的消息是：" + jsonMsg);

        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        String innerCode = supplyContract.getInnerCode();
        List<SupplyChannel> supplyChannels = supplyContract.getSupplyData();
        for (SupplyChannel supplyChannel : supplyChannels) {
            // 查询机器当前货道的容量
            LambdaQueryWrapper<ChannelEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ChannelEntity::getChannelId,supplyChannel.getChannelId())
                              .eq(ChannelEntity::getInnerCode,innerCode);
            ChannelEntity channelEntity = channelService.getOne(lambdaQueryWrapper);
            if (channelEntity == null ){
                throw  new LogicException("当前货道不存在");
            }
            // 获取当前货道容量
            Integer currentCapacityOld = channelEntity.getCurrentCapacity();
            // 最新的货道容量
            Integer currentCapacityNew = currentCapacityOld + supplyChannel.getCapacity();

            LambdaUpdateWrapper<ChannelEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.set(ChannelEntity::getCurrentCapacity,currentCapacityNew)
                               .set(ChannelEntity::getSkuId,supplyChannel.getSkuId())
                               .eq(ChannelEntity::getInnerCode,innerCode)
                               .eq(ChannelEntity::getChannelId,supplyChannel.getChannelId());
            channelService.update(lambdaUpdateWrapper);
        }
    }
}